<template>
  <el-container class="upload-container">
    <el-header>文件上传</el-header>
    <el-main>
      <el-card>
        <h2>上传TXT文件</h2>
        <el-upload
          ref="uploadRef"
          action="#"
          :auto-upload="false"
          :file-list="fileList"
          :on-change="handleFileChange"
          accept=".txt"
          class="mt-4"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">请上传.txt格式的文件</div>
          </template>
        </el-upload>
        <el-button
          type="success"
          class="mt-4"
          :loading="isUploading"
          :disabled="!fileList.length || isUploading"
          @click="uploadFile"
        >
          上传文件
        </el-button>
      </el-card>
      <el-card class="mt-4">
        <template #header>
          <div class="el-card__title">上传结果</div>
        </template>
        <div>
          <p v-for="item in result" :key="item.name">{{ item.name }}</p>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const uploadRef = ref(null)
const fileList = ref([])
const isUploading = ref(false)

// 监听文件变化
const handleFileChange = (uploadFile) => {
  fileList.value = [uploadFile]
}

// 上传文件
const uploadFile = async () => {
  if (!fileList.value.length) {
    ElMessage.warning('请先选择文件')
    return
  }

  const file = fileList.value[0].raw
  if (!file) {
    ElMessage.warning('未找到文件')
    return
  }

  isUploading.value = true

  try {
    // 读取文件内容
    const reader = new FileReader()
    reader.onload = (e) => {
      const content = e.target.result
      const lines = content.split('\n')

      // 发送到主进程解析
      window.api.parseTxtFile(lines)

      ElMessage.success('文件上传成功，已开始解析')
      isUploading.value = false
    }
    reader.onerror = () => {
      ElMessage.error('文件读取失败')
      isUploading.value = false
    }
    reader.readAsText(file)
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败，请重试')
    isUploading.value = false
  }
}
let result = ref([])
// 监听主进程的解析结果
onMounted(() => {
  window.api.onTxtFileParsed((data) => {
    console.log('解析结果:', data)
    data.data.forEach((x) => {
      console.log('name:', x.content.name)
      result.value.put(x.content.name)
    })
    console.log('result:', result.value)
    ElMessage.success('文件解析完成')
  })
})
</script>

<style scoped>
.upload-container {
  height: 100%;
}
.el-header {
  background: #409eff;
  color: white;
  text-align: center;
  line-height: 60px;
}
</style>
